﻿using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Xml;
using Baggr.FeedParser;
using log4net;

namespace Baggr.Agent
{
    using System;
    using System.ServiceProcess;

    public class AgentService
        : ServiceBase
    {
        private IAsyncResult _Result;
        private readonly FeedUpdateTask _Task;
        private readonly ILog _Log = LogManager.GetLogger(typeof(AgentService));
        public AgentService()
        {
            _Log.InfoFormat("Begin constructor");
            ServiceName = "Baggr.Agent";
            CanPauseAndContinue = true;
            CanShutdown = true;
            CanStop = true;
            AutoLog = true;
            var connectionString = ConfigurationManager.ConnectionStrings["agent"].ConnectionString;
            _Log.InfoFormat("Connection string: {0}", connectionString);
            _Task = new FeedUpdateTask(connectionString);
            _Log.InfoFormat("End constructor");
        }
        protected override void OnStart(string[] args)
        {
            _Log.InfoFormat("Begin Start");
            _Result = _Task.BeginExecute(curr => Stop());
            _Log.InfoFormat("End Start");

            base.OnStart(args);
        }
        protected override void OnPause()
        {
            _Log.InfoFormat("Begin Pause");
            _Task.Paused = true;
            _Log.InfoFormat("End Pause");

            base.OnPause();
        }

        protected override void OnContinue()
        {
            _Log.InfoFormat("Begin continue");
            _Task.Paused = false;
            _Log.InfoFormat("End continue");

            base.OnContinue();
        }

        protected override void OnShutdown()
        {
            _Log.InfoFormat("Begin shutdown");
            _Task.Break();
            _Task.EndExecute(_Result);
            _Log.InfoFormat("End shutdown");

            base.OnShutdown();
        }
    }
}
